package com.znufe.exam.controller.h5;

import com.alibaba.fastjson.JSONObject;
import com.znufe.exam.configuration.config.constant.Constants;
import com.znufe.exam.configuration.config.entity.AjaxResult;
import com.znufe.exam.configuration.config.service.SysLoginService;
import com.znufe.exam.configuration.config.utils.SecurityUtils;
import com.znufe.exam.domain.User;
import com.znufe.exam.service.IWxAuthService;
import com.znufe.exam.service.UserService;
import com.znufe.exam.utility.CheckoutUtil;
import com.znufe.exam.utility.HttpClientUtils;
import io.swagger.annotations.Api;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;


@Api(description="微信授权登录接口")
@RestController
@RequestMapping(value = "/wx")
public class H5LoginController {

    @Value("${oauth.wx.appid}")
    private String appId;

    @Value("${oauth.wx.appsecret}")
    private String appSecret;

    @Value("${oauth.callback.http}")
    private String http;

    @Autowired
    private UserService userService;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private IWxAuthService wxAuthService;


    @GetMapping("/openid")
    public Object getOpenid(String code) throws WxErrorException {
        return wxAuthService.getSrvOpenid(code);
    }

    @GetMapping("/userinfo")
    public Object getUserInfo(String code) throws WxErrorException {
        return wxAuthService.getSrvUser(code);
    }

    /*@GetMapping("/login")
    public String wxLogin(){
        // 第一步：用户同意授权，获取code
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId +
                "&redirect_uri=" + http +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=STATE#wechat_redirect";
        *//*try {
            HttpClientUtils.doGet(url);
        } catch (IOException e) {
            e.printStackTrace();
        }*//*

        return url;
    }*/

    /*@GetMapping("/callback")
    public void wxCallBack(String code) throws IOException{
        // 第二步：通过code换取网页授权access_token

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId +
                "&secret=" + appSecret +
                "&code=" + code +
                "&grant_type=authorization_code";
        JSONObject jsonObject = HttpClientUtils.doGet(url);

        String openId = jsonObject.getString("openid");
        String accessToken = jsonObject.getString("access_token");

        // 第四步：拉取用户信息(需scope为 snsapi_userinfo)
        url = "https://api.weixin.qq.com/sns/userinfo?access_token=" +
                accessToken +
                "&openid=" + openId +
                "&lang=zh_CN";
        JSONObject userInfoJson = HttpClientUtils.doGet(url);
        System.out.println(userInfoJson);

        *//**
         * 注册新用户及登录
         *//*
        registWechatUser(userInfoJson);
    }*/

    /*public AjaxResult registWechatUser(JSONObject userInfo) {
        User existUser = userService.selectByWxOpenId(userInfo.getString("openid"));
        System.out.println(existUser.getWxOpenId());
        AjaxResult result = AjaxResult.success();

        // 用户未注册,先注册
        if (null == existUser) {
            User user = new User();
            user.setUserName(userInfo.getString("openid"));
            user.setWxOpenId(userInfo.getString("openid"));
            user.setPassword(SecurityUtils.encryptPassword("123456"));
            user.setUserUuid(UUID.randomUUID().toString());
            user.setCreateTime(new Date());
            user.setStatus(0);
            user.setDeleted(0);
            userService.insertByFilter(user);
        }

        // 注册完成后登录
        User user = userService.selectByWxOpenId(userInfo.getString("openid"));
        String token = loginService.login(user.getUserName(),"123456");
        result.put(Constants.TOKEN, token);
        return result;

    }*/

    //微信消息接收和token验证
    @RequestMapping(value = "/token", method = RequestMethod.GET)
    public String get(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("----------------验证微信服务号信息开始----------");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (CheckoutUtil.checkSignature(signature, timestamp, nonce)) {
            System.out.println("----验证服务号结束.........");
            return echostr;
        }else{
            return null;
        }
    }

}
